# 作者: 家里蹲 吴越洋
# 2023年03月13日15时27分54秒
import struct
from socket import *

class Client:
    def __init__(self,ip,port):
        self.client_socket = None
        self.ip = ip
        self.port = port

    def connection(self):
        client_socket=socket(AF_INET,SOCK_STREAM)
        client_socket.connect((self.ip,self.port))
        self.client_socket=client_socket

    def send_train(self,client_socket:socket,data:str):
            data_bytes=data.encode('utf8')
            data_len=len(data_bytes)
            client_socket.send(struct.pack('I',data_len))
            client_socket.send(data_bytes)

    def recv_train(self):
        train=self.client_socket.recv(4)
        train_content_len=struct.unpack('I',train)[0]
        train_content=self.client_socket.recv(train_content_len)
        return train_content.decode('utf8')

    def do_gets(self):
        # 接文件名
        file_name=self.recv_train()
        # 根据文件名创建文件
        file=open(file_name,'wb')
        train_len=self.client_socket.recv(4)
        file_content_len=struct.unpack('I',train_len)[0]
        total=0
        while total<file_content_len:
            data=self.client_socket.recv(file_content_len-total)
            total+=len(data)
            file.write(data)
        file.close()
        print(f'{file_name}接收成功')

    def do_puts(self,command):
        # 发文件名
        file_name=command[5:]
        file=open(file_name,'r')
        data=file.read().encode('utf8')
        data_len = len(data)
        self.client_socket.send(struct.pack('I', data_len))
        self.client_socket.send(data)
        file.close()
        print(f'{file_name}发送成功')

    def user_operation(self):
        while True:
            command=input()
            self.send_train(self.client_socket,command)
            if command[:4]=='gets':
                self.do_gets()
            elif command[:4]=='puts':
                self.do_puts(command)
            else:
                # 接收数据
                data=self.recv_train()
                # 显示
                print(data,end='')


if __name__ == '__main__':
    c = Client('192.168.0.109', 3000)
    c.connection()
    c.user_operation()